//
//  StoreDetailTableHeaderView.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/14.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "ZZStarView.h"

#import "UIView+shadowPath.h"
#import "StoreDetailCouponReceiveCell.h"
#import "HorizontalCollectionView.h"

#import "StoreDetailTableHeaderView.h"

@interface StoreDetailTableHeaderView ()
<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>{
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
}

@property (nonatomic, strong) ZZStarView *starView;
@property (nonatomic, strong) HorizontalCollectionView *promiseCollectionView;

@end

@implementation StoreDetailTableHeaderView

+ (CGFloat)calculateHeightWithModel:(StoreDetailModel *)model {

    CGFloat toTop = 210;
    
    CGFloat cut = 0;
    if (model.SellerPromiseLabelAuthernticationList.count == 0) {
        cut = cut + 20;
    }
    
    if (model.seller.examStatus != 2) {
        cut = cut + 20;
    }
    
    
    CGFloat infoHeight = 120 - cut;
    
    CGFloat story = 120;
    if (model.seller.sellerStory.length > 0) {
        story = 120;
    } else {
        story = CGFLOAT_MIN;
    }
    
    CGFloat map = 60;
    CGFloat toBottom = 10;

    return toTop + infoHeight + story + map + toBottom;
}

- (void)fillHeaderWithModel:(StoreDetailModel *)model {
    
    self.model = model;
    
    self.starView.grade = model.seller.sellerEvaluateStar;

    if (model.seller.sellerEvaluateStar > 0) {
        self.starCountLab.text = [NSString stringWithFormat:@"%.1f",model.seller.sellerEvaluateStar];
    } else {
        self.starCountLab.text = @"暂无评分";
    }

    //seller
    NSString *imgUrl = model.seller.coverPaths.firstObject.url;
    
    self.storeImageBGView.alpha = 0.f;
    WEAKSELF
    [self.storeImageBGView sd_setImageWithURL:[NSURL URLWithString:imgUrl]  placeholderImage:[UIImage imageNamed:@"placeholder"] options:SDWebImageRetryFailed completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
       
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.storeImageBGView.alpha = 1.f;
        } completion:^(BOOL finished) {
        }];
    }];
    
    NSString *url = [TT_OSSManager reSourceUrl:model.seller.logoUrl type:BA_resizeType_plus];
    [self.storeIcon sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    self.storeName.text = model.seller.sellerName;
    self.couponCountLab.text = [NSString stringWithFormat:@"共%lu张券",(unsigned long)model.sysCouponList.count];
    
    self.addressLab.text = model.seller.sellerAddress;
    
    self.storeStoryContent.text = model.seller.sellerStory;
    
    if (model.seller.sellerStory.length > 0) {
        self.storeStoryHeight.constant = 120;
    } else {
        self.storeStoryHeight.constant = CGFLOAT_MIN;
    }
    
    if (model.seller.lat > 0) {
        
        if (model.seller.distance < 1000) {
            self.markLab.text = [NSString stringWithFormat:@"距您%.fm | (进店请电联哦)",model.seller.distance];
        } else {
            self.markLab.text = [NSString stringWithFormat:@"距您%.fkm | (进店请电联哦)",model.seller.distance/1000];
        }
    } else {
        self.markLab.text = @"(进店请电联哦)";
    }
    
    [self.promiseCollectionView fillPromiseData:model.SellerPromiseLabelAuthernticationList];

    if (model.SellerPromiseLabelAuthernticationList.count == 0) {
        self.promiseHeight.constant = CGFLOAT_MIN;
    }
    

    
    self.wyxIcon1.hidden = YES;
    self.wyxLab1.hidden = YES;
    self.wyxIcon2.hidden = YES;
    self.wyxLab2.hidden = YES;
    self.wyxIcon3.hidden = YES;
    self.wyxLab3.hidden = YES;
    if (model.seller.examStatus == 2) {
        self.wuyouxuanControl.hidden = NO;
        self.wyxHeight.constant = 20.0f;
        
        for (int i = 0; i < model.sysWorryFreeLabel.count; i++) {
            if (i == 0) {
                self.wyxIcon1.hidden = NO;
                self.wyxLab1.hidden = NO;
                self.wyxLab1.text = model.sysWorryFreeLabel[i].labelName;
            }
            if (i == 1) {
                self.wyxIcon2.hidden = NO;
                self.wyxLab2.hidden = NO;
                self.wyxLab2.text = model.sysWorryFreeLabel[i].labelName;
            }
            if (i == 2) {
                self.wyxIcon3.hidden = NO;
                self.wyxLab3.hidden = NO;
                self.wyxLab3.text = model.sysWorryFreeLabel[i].labelName;
            }
        }
        
    } else {
        self.wuyouxuanControl.hidden = YES;
        self.goWYXBtn.hidden = YES;
        self.wyxHeight.constant = CGFLOAT_MIN;
    }

    self.countDescLab.text = [NSString stringWithFormat:@"%ld条 %ld关注",(long)self.model.seller.sellerCount,self.model.seller.collectionCount];
    
    CGFloat cut = 0;
    if (model.SellerPromiseLabelAuthernticationList.count == 0) {
        cut = cut + 20;
    }
    if (model.seller.examStatus != 2) {
        cut = cut + 20;
    }
    self.infoBGHeight.constant = 120 - cut;
    
    [self.collectionview reloadData];
    
    self.starView.hidden = YES;
    self.starCountLab.text = @"";
    self.countDescLab.text = @"";
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.storeIcon pp_clipCorners:UIRectCornerAllCorners radius:6];
        [self.storeMapView pp_clipCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight radius:6];
    });
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self.storeStarBgView addSubview:self.starView];

    [self.starView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    
    layer.colors = @[(__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0].CGColor, (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:1].CGColor];
    
    layer.frame = CGRectMake(0, self.storeImageBGView.frame.size.height/2, self.storeImageBGView.frame.size.width, self.storeImageBGView.frame.size.height/2);
    [self.storeImageBGView.layer insertSublayer:layer atIndex:0];


    [self.storeMapBGImageView viewShadowPathWithColor:[UIColor blackColor] shadowOpacity:0.5 shadowRadius:6 shadowPathType:LeShadowPathBottom shadowPathWidth:4];
    
    self.wuyouxuanControl.userInteractionEnabled = YES;
    self.mapNaviControl.userInteractionEnabled = YES;
    WEAKSELF
    [self.wuyouxuanControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        if (weakSelf.StoreDetailTableHeaderViewBlock) {
            weakSelf.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_wuyouxuan,0);
        }
    }];
    
    [self.wyxControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        if (weakSelf.StoreDetailTableHeaderViewBlock) {
            weakSelf.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_wuyouxuan,0);
        }
    }];
    
    [self.storeStoryBGView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        if (weakSelf.StoreDetailTableHeaderViewBlock) {
            weakSelf.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_story,0);
        }
    }];
    
    [self.mapNaviControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        if (weakSelf.StoreDetailTableHeaderViewBlock) {
            weakSelf.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_mapNavi,0);
        }
    }];
    
    [self.lookMoreControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        if (weakSelf.StoreDetailTableHeaderViewBlock) {
            weakSelf.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_video,0);
        }
    }];

    
    CGFloat distance = 5;
    CGFloat height = 80;
    CGFloat width = 80 * 2.3;

    _cellSize =  CGSizeMake(width, height);
    _collectionEdge = UIEdgeInsetsMake(distance, distance, distance, distance);
    
    UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc]init];
    flowLaout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.collectionview.collectionViewLayout = flowLaout;
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    self.collectionview.showsHorizontalScrollIndicator = NO;
    self.collectionview.showsVerticalScrollIndicator = NO;
    
    [self.collectionview registerNib:[UINib nibWithNibName:@"StoreDetailCouponReceiveCell" bundle:nil] forCellWithReuseIdentifier:@"StoreDetailCouponReceiveCellID"];
    
    [self.promiseBGView addSubview:self.promiseCollectionView];
    [self.promiseCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    StoreDetailCouponReceiveCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StoreDetailCouponReceiveCellID" forIndexPath:indexPath];
    [cell fillCellWitModel:self.model.sysCouponList[indexPath.row]];

    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.model.sysCouponList.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return _cellSize;
}

//设置cell的位置
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section {

    return _collectionEdge;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (self.StoreDetailTableHeaderViewBlock) {
        self.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_coupon, indexPath.row);
    }
}


- (IBAction)infoClickAction:(id)sender {
    
    if (self.StoreDetailTableHeaderViewBlock) {
        self.StoreDetailTableHeaderViewBlock(StoreDetailTableHeaderType_wuyouxuan, 0);
    }
}

- (ZZStarView *)starView {
    
    if (!_starView) {

        _starView = [[ZZStarView alloc] initWithImage:[UIImage imageNamed:@"daxing_nor"] selectImage:[UIImage imageNamed:@"daxing_sel"] starWidth:12 starHeight:12 starMargin:2 starCount:5 callBack:^(CGFloat userGrade, CGFloat finalGrade) {
        }];
        //默认值, 可以不写, 用户可选分值范围是0.5的倍数.(建议在设置分值之前确定此值)
        _starView.sublevel = 0.5;
        //设置分值, 可以不写, 默认显示0分.(self.params是UIViewController在ZZRouter中扩展的属性, 包含了所有参数)
        _starView.grade = 0.0;
        //最小值, 默认0.5可以不写, 用户可以设置的最低分值.
        _starView.miniGrade = 0;
        _starView.frame = CGRectMake(0, 0, 70, 14);

    }
    return _starView;
}

- (HorizontalCollectionView *)promiseCollectionView {
    if (!_promiseCollectionView) {
        _promiseCollectionView = [[HorizontalCollectionView alloc] initWithType:HorizontalCollectionType_storeDetail];
    }
    return _promiseCollectionView;
}

@end
